package com.wodan.zhongjinjicang.common.orm.command.read;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import com.wodan.zhongjinjicang.common.orm.metadata.TableFieldMetaData;
import com.wodan.zhongjinjicang.common.orm.metadata.TableMetaData;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.Assert;



public class BeanRowMapper implements RowMapper<Object> {
	private final TableMetaData tableMetaData;
	
	private final TypeHandlerRegistry typeHandlerRegistry;
	
	public BeanRowMapper(TableMetaData tableMetaData, TypeHandlerRegistry typeHandlerRegistry) {
		Assert.notNull(tableMetaData);
		Assert.notNull(typeHandlerRegistry);
		
		this.tableMetaData = tableMetaData;
		this.typeHandlerRegistry = typeHandlerRegistry;
	}
	
	@Override
	public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		Object resultBean = tableMetaData.instantiateNewEntityBean();

		ResultSetMetaData metaData = rs.getMetaData();
		int columnCount = metaData.getColumnCount();

		for (int i = 1; i <= columnCount; i++) {
			String columnName = metaData.getColumnName(i);
			TableFieldMetaData field = tableMetaData.getFieldByColumnName(columnName);
			if (field != null) {
				
				Class<?> javaType = field.getFieldObjetClass();
				TypeHandler<?> typeHandler = typeHandlerRegistry.getTypeHandler(javaType);
				Object value = typeHandler.getResult(rs, i);
				field.writeFieldValue(resultBean, value);
			}
		}

		return resultBean;
	}
}
